package cn.edu.njuit.web.server.apis;


import cn.edu.njuit.web.server.config.BaiduAiProperties;
import com.baidu.aip.nlp.AipNlp;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Controller
public class Lesson6Api {
    @GetMapping("/api/hello")
    public  void HelloWorld(HttpServletRequest req, HttpServletResponse resp) {
        try {
            resp.getWriter().write("I LOVE YOU");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    BaiduAiProperties baiduAiProperties;

    @GetMapping("/api/ai")
    public void baiduAi(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/plain;charset=utf8");
        //传递一句话
        String text=req.getParameter("keyword");
        //得到一句话，调用百度ai完成判定
        if(text!=null){
            AipNlp client = new AipNlp(
                    baiduAiProperties.getAppId(),
                    baiduAiProperties.getApiKey(),
                    baiduAiProperties.getSecretKey());
            // 传入可选参数调用接口
            HashMap<String, Object> options = new HashMap<String, Object>();
            // 情感倾向分析
            JSONObject res = client.sentimentClassify(text, options);
            resp.getWriter().write(res.toString(2));

        } else{
            resp.getWriter().write("请输入一句话进行判定");
        }

    }
}
